import { Button, Card, message, Popconfirm, Space } from "antd";
import { Component } from "../../domain/Component";
import styles from "./ListItem.module.css";
import Meta from "antd/es/card/Meta";
import { ws } from "../../utils/websocket";
import { apiRoute, BASE_URL } from "../../utils/api";

export const ListItem = (props: {
  components: Component[];
  refreshList: () => void;
}) => {
  const chooseComponent = (item: Component) => {
    ws.sendObj("useComponent", item.name, (data) => {
      message.success(data.data);
    });
  };

  const delComponent = (id: number) => {
    fetch(
      apiRoute("delComponent") +
        "?" +
        new URLSearchParams({ id } as any).toString()
    )
      .then((data) => data.json())
      .then((data) => {
        console.log(data);
        message.success("删除成功");
        props.refreshList();
      });
  };

  return (
    <div className={styles.box}>
      {props.components.map((item) => {
        return (
          <div key={item.id} className={styles.card}>
            <Card
              hoverable
              style={{ width: 300, height: 397, marginBottom: 10 }}
              // onClick={() => chooseComponent(item)}
              cover={
                <div className={styles.cover}>
                  <img
                    alt="example"
                    style={{ maxHeight: "100%", maxWidth: "100%" }}
                    src={
                      item.thumbnail
                        ? BASE_URL + "upload/" + item.thumbnail
                        : "/react.png"
                    }
                  />
                </div>
              }
            >
              <div className={styles.meta}>
                <Meta title={item.label} description={item.description} />
              </div>

              <Space>
                <Popconfirm
                  title="使用该模块？"
                  onConfirm={() => chooseComponent(item)}
                  placement="bottom"
                  cancelText="取消"
                  okText="确定"
                >
                  <Button type="primary">使用</Button>
                </Popconfirm>
                <Button
                  onClick={() => {
                    delComponent(item.id);
                  }}
                  type="primary"
                  danger
                >
                  删除
                </Button>
              </Space>
            </Card>
          </div>
        );
      })}
    </div>
  );
};
